#!/bin/bash

TMP=$(dirname $0)

# 加载工具类
. ${TMP}/files/etc/idnewnil/utils.sh
load_config ${TMP}/files/etc/idnewnil/config.json

getenv '.'

# 下载镜像构建工具进行解压，然后进入该目录
VERSION=$(getstr '.version')
ARCHITECTURE=$(getstr '.architecture')
CHIP=$(getstr '.chip')
BUILDER=openwrt-imagebuilder-${VERSION}-${ARCHITECTURE}-${CHIP}.Linux-x86_64
BUILDER_TAR=${BUILDER}.tar.xz
BUILDER_URL=https://downloads.openwrt.org/releases/${VERSION}/targets/${ARCHITECTURE}/${CHIP}/${BUILDER_TAR}
if [ ! -d ${BUILDER}/ ]; then
    if [ ! -f ${BUILDER_TAR} ]; then
        wget ${BUILDER_URL}
    fi
    tar xf ${BUILDER_TAR}
fi
cd ${BUILDER}/

# 复制所需文件
rm -rf files/
cp -r ${TMP}/files/ ./

# 定义需要安装的软件
SYSTEM="coreutils-sleep"                                                                       # 增强系统功能
SETUP="jq"                                                                                     # 初次启动运行脚本所需要的环境
LUCI="luci luci-i18n-base-zh-cn luci-i18n-opkg-zh-cn luci-i18n-firewall-zh-cn"                 # 界面和汉化包
USB="block-mount e2fsprogs kmod-fs-ext4 kmod-usb-storage kmod-usb2 kmod-usb3 parted"           # U盘挂载
CERT="openssl-util luci-i18n-acme-zh-cn acme-dnsapi"                                           # 生成证书
DDNS="luci-i18n-ddns-zh-cn ddns-scripts-cloudflare"                                            # 动态dns
FRP="luci-i18n-frpc-zh-cn"                                                                     # 内网穿透
COMMANDS="luci-i18n-commands-zh-cn"                                                            # 自定义命令
UPNP="luci-i18n-upnp-zh-cn"                                                                    # upnp
WOL="luci-i18n-wol-zh-cn"                                                                      # 网络唤醒
PACKAGES="${SYSTEM} ${SETUP} ${LUCI} ${USB} ${CERT} ${DDNS} ${UPNP} ${FRP} ${WOL} ${COMMANDS}" # 所有包

# 执行构建命令
PROFILE=$(getstr '.profile')
make image PROFILE=${PROFILE} PACKAGES="${PACKAGES}" FILES="files"

# 显示scp命令
if [ $? -eq 0 ]; then
    echo "输入以下命令之一复制镜像到桌面："
    echo -e "公网：\033[32mscp -r root@$(curl ifconfig.me 2>/dev/null):${PWD}/bin/targets/ desktop/\033[0m"
    DEV=$(ip r | awk '$1 == "default" {print $5}')
    DEFAULT_IP=$(ip addr show dev ${DEV} | grep -Po '(?<=inet )\d{1,3}\.\d{1,3}.\d{1,3}.\d{1,3}')
    echo -e "局域网：\033[32mscp -r root@${DEFAULT_IP}:${PWD}/bin/targets/ desktop/\033[0m"
else
    echo -e "\033[31m构建失败。\033[0m"
fi
